<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AppService
 *
 * @author Administrator
 */
import('@.Service.AppFileService');
import('@.Service.AppTypeService');
import('@.Service.TypeService');
import('@.Service.ConfigService');
import('@.Service.UrlsService');
import('@.Util.ConstantUtil');
vendor('simplehtmldom.simple_html_dom');

class AppService {

    /**
     * 获取本周最热门下载
     * @return type 
     */
    function getAppListByWeekHot() {
        $list = S('AppService_getAppListByWeekHot');
        if (!empty($list)) {
            return $list;
        }

        $week = date('w');
        $weekDay = array();
        for ($index = 1; $index < 8; $index++) {
            array_push($weekDay, date('Y-m-d', strtotime('+' . $index - $week . ' days')));
        }

        $appTable = D('app');
        $map['date'] = array('in', $weekDay);

        //已发布
        $map['app.release'] = array('eq', 1);
        $list = $appTable->where($map)->order('download_num desc')->limit(5)->select();

        //本周内为空，按下载顺序排列
        if (empty($list)) {
            $list = $appTable->where(array('app.release' => 1))->order('download_num desc')->limit(5)->select();
        }

        S('AppService_getAppListByWeekHot', $list, ConstantUtil::$CACHE_TIME);

        return $list;
    }

    function listAppListByType($field = 'app.*') {
        $result = S(ConstantUtil::$SERVICE_APPSERVICE_LISTAPPLISTBYTYPE);
        if (!empty($result)) {
            return $result;
        }

        $filter = ' and a.price is not null and a.size is not null and a.download_url is not null and a.app_icon is not null';
        $appTable = D('app');
        $list = $appTable->query('select t.id t_id, t.name t_name, count(*) app_count from app a join app_type at on a.id = at.app_id join type t on t.id = at.type_id where t.root is null ' . $filter . ' group by t.id');


        $result = array();
        foreach ($list as $l) {
            $app = $this->findFirstTypeAppById($l['t_id'], $field);
            $free_count = $this->countFreeAppByTypeId($l['t_id']);
            array_push($result, array('t_id' => $l['t_id'], 't_name' => $l['t_name'], 'count' => $l['app_count'], 'free_count' => $free_count, 'app_icon' => $app['app_icon']));
        }

        S(ConstantUtil::$SERVICE_APPSERVICE_LISTAPPLISTBYTYPE, $result, ConstantUtil::$CACHE_TIME);

        return $result;
    }

    /**
     * 小类型下的免费App数
     * @param type $typeId 
     */
    function countFreeAppByTypeId($typeId, $release = 1) {
        $appTable = D('app');
        $where['t.id'] = array('eq', $typeId);
        $where['app.release'] = array('eq', $release);
        $where['app.tag'] = array('like', '%免费%');
        $result = $appTable->join('app_type at on app.id = at.app_id')
                ->join('type t on at.type_id = t.id')
                ->where($where)
                ->count();
        return $result;
    }

    /**
     * 获取本日最热门下载
     * @return type 
     */
    function getAppListByDayHot() {
        $list = S('AppService_getAppListByDayHot');
        if (!empty($list)) {
            return $list;
        }
        $appTable = D('app');
        $date = date('Y-m-d');

        $map['date'] = $date;

        //已发布
        $map['app.release'] = array('eq', 1);
        $list = $appTable->where($map)->order('download_num desc')->limit(5)->select();

        if (empty($list)) {
            $list = $appTable->where(array('app.release' => 1))->order('download_num desc')->limit(5)->select();
        }
        S('AppService_getAppListByDayHot', $list, ConstantUtil::$CACHE_TIME);

        return $list;
    }

    /**
     * 首页上热门
     * @param type $typeName 类型名 
     */
    function listAppHotByTypeName($typeName, $limit) {
        $appTable = D('app');
        $typeService = new TypeService();
        $tId = $typeService->getTypeIdByName($typeName);

        $list = $appTable->join('app_type at on app.id = at.app_id')
                        ->join('type t on at.type_id = t.id')
                        ->field('app.*')
                        ->where("(app.app_icon is not null and t.type_id = " . $tId . " and app.release = 1)")
                        ->order('app.download_num desc')
                        ->distinct(true)->limit($limit)->select();
        return $list;
    }

    /**
     * 首页上最新游戏和应用
     * @param type $typeName 
     */
    function listAppNewByTypeName($typeName, $offset, $limit) {
        $appTable = D('app');
        $typeService = new TypeService();
        $tId = $typeService->getTypeIdByName($typeName);

        $list = $appTable->join('app_type at on app.id = at.app_id')
                        ->join('type t on at.type_id = t.id')
                        ->field('app.*')
                        ->where("app.release = 1 and t.type_id = " . $tId)
                        ->order('app.datetime desc')->limit($offset . ',' . $limit)->select();
        return $list;
    }

    /**
     * 首页上再次免费应用
     */
    function listAppFreeAgain() {
        $appTable = D('app');

        $where['fine'] = 1;

        $list = $appTable->where($where)->limit(12)->order('datetime desc')->select();

        return $list;
    }

    /**
     * 更新
     * @param type $app 
     */
    function save($app) {
        $appTable = D('app');

        $appTable->startTrans();

        $appTypeService = new AppTypeService();

        $typeIdList = $app['typesIdList'];
        if (!empty($typeIdList)) {
            $appTypeService->deleteByAppIdList();

            $appTypeService->insertAllByTypeId($app['id'], $typesIdList);
        }

        $lastId = $appTable->save($app);

        $appTable->commit();

        return $lastId;
    }

    /**
     * 手工发布App信息
     * @param type $app 
     */
    function insert($app) {
        $appTable = D('app');

        $appTable->startTrans();

        $app['datetime'] = date('Y-m-d H:m:s');
        $app['date'] = date('Y-m-d');

        //设定查看和下载量
        $app['see_num'] = rand(10000, 20000);
        $app['download_num'] = rand(3000, 10000);

        // type id
        $typesIdList = $app['typesIdList'];
        if (!empty($typesIdList)) {
            $typeService = new TypeService();
            $typeNames = $typeService->listTypeNameByIds($typesIdList, 'name');

            $tag = '';
            foreach ($typeNames as $type) {
                $tag .= $type['name'] . ' ';
            }

            $app['tag'] = $tag;
        }


        $lastId = $appTable->add($app);


        if (!empty($typesIdList)) {
            //添加App和类型关联
            $appTypeService = new AppTypeService();

            $appTypeService->insertAllByTypeId($lastId, $typesIdList);
        }

        // file id
        $fileIdList = $app['fileIdList'];
        if (!empty($fileIdList)) {

            $appFileService = new AppFileService();
            $appFileService->insert($lastId, $fileIdList);
        }

        $appTable->commit();
    }

    //替换 管理台使用 countAppByTypeName 方法
    function countApp1($appName, $release = 1) {
        $where;
        if (!is_null($release)) {
            $where['release'] = array('eq', $release);
        }
        if (!is_null($appName)) {
            $where['app.name'] = array('like', '%' . $appName . '%');
        }
        return D('app')->where($where)->count();
    }

    //替换 管理台使用 listAppByTypeName 方法
    function listApp1($appName, $limit, $release = 1, $field = 'app.*', $order='datetime desc') {
        $where;
        if (!is_null($release)) {
            $where['release'] = array('eq', $release);
        }
        if (!is_null($appName)) {
            $where['app.name'] = array('like', '%' . $appName . '%');
        }
        return D('app')->field($field)->where($where)
                        ->limit($limit)->order($order)
                        ->select();
    }

    /**
     * 计数
     * @param type $typeName
     * @param type $appName
     * @return type 
     */
    function countAppByTypeName($typeName, $appName, $release = 1) {

        $typeService = new TypeService();
        $typeId = $typeService->getTypeIdByName($typeName);

//        $appTable = D('app');
//        $where['t.type_id'] = array('eq', $typeId);
//        //模糊搜索字符串不为空
//        if (!empty($appName)) {
//            $where['app.name'] = array('like', '%' . $appName . '%');
//        }
//
//        $result = $appTable->join('app_type at on app.id = at.app_id')
//                ->join('type t on at.type_id = t.id')->Distinct(true)
//                ->field('app.id')
//                ->where($where)
//                ->count();

        $appModel = new Model();

        $query = '';
        //过滤信息不全的App
//        $where['app.price'] = array('exp', 'is not null');
//        $where['app.size'] = array('exp', 'is not null');
//        $where['app.download_url'] = array('exp', 'is not null');
//        $where['app.app_icon'] = array('exp', 'is not null');
//        $filter = ' and app.price is not null and app.size is not null and app.download_url is not null and app.app_icon is not null ';

        if (is_null($release)) {
            $query = "SELECT COUNT(DISTINCT app.id ) AS app_count FROM `app` LEFT JOIN app_type at on app.id = at.app_id LEFT JOIN type t on at.type_id = t.id WHERE ( t.type_id = '" . $typeId . "')";
        } else {

            $query = "SELECT COUNT(DISTINCT app.id ) AS app_count FROM `app` LEFT JOIN app_type at on app.id = at.app_id LEFT JOIN type t on at.type_id = t.id WHERE ( t.type_id = '" . $typeId . "' and app.release = " . $release . ")  ";
        }
        if (!is_null($appName)) {
            $query.=" AND ( app.name LIKE '%" . $appName . "%' )";
        }
        $result = $appModel->query($query);


//        dump($appModel->getLastSql());
//        dump($appTable->getLastSql());
        return $result[0]['app_count'];
    }

    function findAppById($id, $fields = '*') {
        return D('app')->field($fields)->find($id);
    }

    function countSearch($name, $release = 1) {
        $where['name'] = array('like', '%' . $name . '%');
        $where['release'] = array('eq', $release);
        return D('app')->where($where)->count();
    }

    /**
     * 模糊查找
     * @param type $name
     * @param type $limit
     * @param type $release 
     */
    function search($name, $limit, $field = '*', $order='datetime desc', $release = 1) {
        $where['name'] = array('like', '%' . $name . '%');
        $where['release'] = array('eq', $release);
        return D('app')->where($where)->field($field)->order($order)->limit($limit)->select();
    }

    function findAppByUrl($url) {
        $where['url'] = array('eq', $url);

        return D('app')->where($where)->find();
    }

    function findAppAndTypeById($id) {
        $app = $this->findAppById($id);
        $appTypeSerice = new AppTypeService();
        $typeIds = $appTypeSerice->listTypeIdByAppId($id);

        $a = $app;
        $a['type_id'] = $this->joinTypeId($typeIds);

        return $a;
    }

    private function joinTypeId($typeIds) {
        if (is_null($typeIds)) {
            return '';
        }

        $typeId = '';
        foreach ($typeIds as $k => $value) {
            $typeId .= $value['type_id'] . ',';
        }

        return $typeId;
    }

    /**
     * 应用 游戏App 并支持模糊查询
     * @param type $typeName
     * @param type $offset
     * @param type $limit
     * @param type $order 
     */
    function listAppByTypeName($typeName, $appName, $offset, $limit, $order, $release = 1, $field = 'app.*') {
        $typeService = new TypeService();
        $typeId = $typeService->getTypeIdByName($typeName);

        $appTable = D('app');
        $where['t.type_id'] = array('eq', $typeId);

        //过滤信息不全的App
//        $where['app.price'] = array('exp', 'is not null');
//        $where['app.size'] = array('exp', 'is not null');
//        $where['app.download_url'] = array('exp', 'is not null');
//        $where['app.app_icon'] = array('exp', 'is not null');

        if (!is_null($release)) {
            $where['app.release'] = array('eq', $release);
        }
        //模糊搜索字符串不为空
        if (!empty($appName)) {
            $where['app.name'] = array('like', '%' . $appName . '%');
        }
        $result = $appTable->join('app_type at on app.id = at.app_id')
                ->join('type t on at.type_id = t.id')
                ->field($field)
                ->where($where)
                ->limit($offset . ',' . $limit)
                ->order($order)
                ->Distinct(true)
                ->select();

//        echo $appTable->getLastSql();
        return $result;
    }

    /**
     * 分页 总数
     * @param type $typeName
     * @param type $appName 
     */
    function countAppBySmallTypeName($typeName, $appName, $release = 1) {
        $appTable = D('app');
        $where['t.name'] = array('eq', $typeName);

//        //过滤信息不全的App
//        $where['app.price'] = array('exp', 'is not null');
//        $where['app.size'] = array('exp', 'is not null');
//        $where['app.download_url'] = array('exp', 'is not null');
//        $where['app.app_icon'] = array('exp', 'is not null');




        if (!is_null($release)) {
            $where['app.release'] = array('eq', $release);
        }
        //模糊搜索字符串不为空
        if (!empty($appName)) {
            $where['app.name'] = array('like', '%' . $appName . '%');
        }
        $result = $appTable->join('app_type at on app.id = at.app_id')
                ->join('type t on at.type_id = t.id')
                ->field('app.*')
                ->where($where)
                ->count();
        return $result;
    }

    /**
     * 返回  小类中第 一个 App
     */
    function findFirstTypeAppById($typeId, $field, $release = 1) {
        $appTable = D('app');
        $where['t.id'] = array('eq', $typeId);
        $where['app.release'] = array('eq', $release);
        $result = $appTable->join('app_type at on app.id = at.app_id')
                ->join('type t on at.type_id = t.id')
                ->where($where)
                ->field($field)
                ->order('datetime desc')
                ->limit(1)
                ->find();
        return $result;
    }

    /**
     * 根据小类型查询
     * @param type $typeName
     * @param type $appName
     * @param type $offset
     * @param type $limit
     * @param type $order
     * @return type 
     */
    function listAppBySmallTypeName($typeName, $appName, $offset, $limit, $order, $release = 1, $field = 'app.*') {
        $appTable = D('app');
        $where['t.name'] = array('eq', $typeName);

        //过滤信息不全的App
//        $where['app.price'] = array('exp', 'is not null');
//        $where['app.size'] = array('exp', 'is not null');
//        $where['app.download_url'] = array('exp', 'is not null');
//        $where['app.app_icon'] = array('exp', 'is not null');
        if (!is_null($release)) {
            $where['app.release'] = array('eq', $release);
        }
        //模糊搜索字符串不为空
        if (!empty($appName)) {
            $where['app.name'] = array('like', '%' . $appName . '%');
        }
        $result = $appTable->join('app_type at on app.id = at.app_id')
                ->join('type t on at.type_id = t.id')
                ->field($field)
                ->where($where)
                ->limit($offset . ',' . $limit)
                ->order($order)
                ->Distinct(true)
                ->select();
        return $result;
    }

    /**
     * 关键字查询
     * @param type $appName 
     */
    function countAppByAppName($appName, $release = 1) {
        $appTable = D('app');
        $where['name'] = array('like', '%' . $appName . '%');
        if (!is_null($release)) {
            $where['app.release'] = array('eq', $release);
        }

        return $appTable->where($where)->count();
    }

    /**
     * 根据查询关键字对文件名文件内容进行模糊查询
     * @param type $appName
     * @param type $offset
     * @param type $limit
     * @param type $order
     * @return type 
     */
    function listAppByAppName($appName, $offset, $limit, $order, $field='*', $release = 1) {
        $appTable = D('app');
        $where['name'] = array('like', '%' . $appName . '%');
        if (!is_null($release)) {
            $where['app.release'] = array('eq', $release);
        }
//        $where['content'] = array('like', '%' . $appName . '%');
//        $where['_logic'] = 'or';


        return $appTable->field($field)->where($where)->limit($offset . ',' . $limit)
                        ->order($order)->select();
    }

    function updateAutoLoad($id, $app) {
        $appTable = D('app');
        $appTable->startTrans();
        $appO = $appTable->find($id);
        if (empty($appO)) {
            return 0;
        }
        $appO['name'] = $app['name'];
        $appO['content'] = $app['content'];
        $appO['release'] = $app['release'];

        $lastId = $appTable->save($appO);

        $appTable->commit();

        return $lastId;
    }

    /**
     * 下载量最高的App
     * @param type $limit
     * @return type 
     */
    function listAppByDownLoadNum($limit, $release = 1) {
        $appTable = D('app');
        if (!is_null($release)) {
            $where['app.release'] = array('eq', $release);
        }
        return $appTable->field('id, download_num')->where($where)->order('download_num desc')->limit($limit)->select();
    }

    /**
     * App 删除
     * @param type $id 
     */
    function deleteApp($id) {
        $appTable = D('app');
        $appTable->startTrans();

        $appType = new AppTypeService();
        $appType->deleteByAppId($id);

        $lastId = $appTable->where(array('id' => $id))->delete();

        $appTable->commit();
        return $lastId;
    }

    /**
     *  更新App
     * @param type $app
     * @return type 
     */
    function updateApp($app) {
        $appTable = D('app');
        $appTable->startTrans();

        $lastId = $appTable->where(array('id' => $app['id']))->save($app);

        $appTable->commit();
        return $lastId;
    }

    function insertReleaseApp($url, $fine = 0) {
        $appTable = D('app');

        $appTable->startTrans();
        $app = $this->getAppContent($url['url']);

        if (!$app) {
            //未解析出当前地址
            return false;
        }

        $app['fine'] = $fine;
        $app['date'] = date('Y-m-d');
        //抓取的数据路径
        $app['load_url'] = $url['url'];

        //设定查看和下载量
        $app['see_num'] = rand(10000, 20000);
        $app['download_num'] = rand(3000, 10000);
        //当前数据为自动抓取
        $app['auto_load'] = 1;
        //是否自动发布

        $configService = new ConfigService();
        $app['release'] = $configService->getConfigValue('auto_release');
        //当前抓取的数据是否缺少信息
        $app = $this->getRelease($app, array('name', 'price', 'size', 'app_icon', 'download_url'));

        $lastId = $appTable->data($app)->add();
        $types = $app['types'];
        if (!empty($types)) {
            //添加App和类型关联
            $appTypeService = new AppTypeService();
            $appTypeService->insertAllByTypeName($lastId, $types);
        }
        $url['load_over'] = 1;

        //将此条Url更新为读取完毕
//        $urlTable->save($url);
        $urlsService = new UrlsService();
        $urlsService->updateUrls($url['id']);

        $appTable->commit();
    }

    private function getRelease($app, $fields) {
        foreach ($fields as $field) {
            if (empty($app[$field])) {
                $app['release'] = 0;
                break;
            }
        }

        return $app;
    }

    /**
     * 添加自动拉取数据
     * @return type 
     */
    function releaseApps() {


        $urlsService = new UrlsService();
        $url = $urlsService->findReleaseByType('app');

        if (empty($url)) {
            return false;
        }

        $this->insertReleaseApp($url);
        return true;
    }

    /**
     * 统计所有App
     * @return type 
     */
    function countAllApp() {
        $appTable = D('app');

        return number_format($appTable->where(array('release' => 1))->count(), 0, ",", ",");
    }

    function count() {
        return D('app')->count();
    }

    /**
     * 统计所有App 下载总数
     */
    function countAllAppDownLoadNum() {
        $result = S('AppService/countAllAppDownLoadNum');
        if (!$result) {
            $appTable = D('app');
            $result = number_format($appTable->sum('download_num'), 0, ",", ",");
            S('AppService/countAllAppDownLoadNum', $result);
        }

        return $result;
    }

    /**
     * 今天发布的App
     */
    function countReleaseAppByToday() {
        $result = S('AppService/countReleaseAppByToday');
        if (!$result) {
            $appTable = D('app');
            $where['release'] = array('eq', 1);
            $where['date'] = array('eq', date('Y-m-d'));
            $result = number_format($appTable->where($where)->count(), 0, ",", ",");

            S('AppService/countReleaseAppByToday', $result);
        }

        return $result;
    }

    function getAppContent($url) {
        $app = array();

        $html = file_get_html($url);
        if (!$html) {
            return $html;
        }
        //获取时间
        $leftDiv = $html->find("#colLeft div.metaLeft");

        $app['datetime'] = date('Y-m-d H:m:s');

        //获取内容
        $rightDiv = $html->find("#colLeft div.postRight");
        $d = array_shift($rightDiv);
        // echo $appPhoto;return;
        // 


        $script = $d->find('p script');
        // has flash
        if (!empty($script)) {
            $flashText = '<script>';
            foreach ($script as $s) {
                $flashText .= $s->innertext();
            }
            $flashText.= '</script>';

            $app['flash'] = $flashText;
        }


        $appIcon = $d->find('table.app-icon-line');
        if (!empty($appIcon)) {
            $appIcon = array_shift($appIcon);

            $app['app_icon'] = array_shift($appIcon->find('img'))->attr['src'];
            //适合使用的设备
            $app['app_icon_type'] = array_shift($appIcon->find('td.app-icon-type img'))->attr['src'];
            $appInfoText = $appIcon->text();

            //$appInfoTextArray = split(' ', str_replace('&nbsp;', '', trim($appInfoText)));
            preg_match_all("/[^\s　]+/s", str_replace('&nbsp;', '', trim($appInfoText)), $appInfoTextArray);
            if (7 == count($appInfoTextArray[0])) {
                for ($i = 0; $i < count($appInfoTextArray[0]); $i++) {
                    if ($appInfoTextArray[0][$i] == '价格:') {
                        $app['price'] = $appInfoTextArray[0][$i + 1];
                    } elseif ($appInfoTextArray[0][$i] == '大小:') {
                        $app['size'] = $appInfoTextArray[0][$i + 1];
                    } elseif ($appInfoTextArray[0][$i] == '系统:') {
                        $app['version'] = $appInfoTextArray[0][$i + 1];
                    }
                }
            } elseif (4 == count($appInfoTextArray[0]) || 3 == count($appInfoTextArray[0])) {
                for ($i = 0; $i < count($appInfoTextArray[0]); $i++) {
                    if (ereg('^价格', $appInfoTextArray[0][$i])) {
                        $app['price'] = $this->subAppText($appInfoTextArray[0][$i]);
                    } else if (ereg('^系统', $appInfoTextArray[0][$i])) {
                        $app['version'] = $this->subAppText($appInfoTextArray[0][$i]);
                    } else if (ereg('^大小', $appInfoTextArray[0][$i])) {
                        $app['size'] = $this->subAppText($appInfoTextArray[0][$i]);
                    }
                }
            }
//            dump($appInfoTextArray);
//            return;
//            foreach ($appInfoTextArray as $info) {
//                if (ereg('^价格', $info)) {
//                    $app['price'] = $this->subAppText($info);
//                } else if (ereg('^系统', $info)) {
//                    $app['version'] = $this->subAppText($info);
//                } else if (ereg('^大小', $info)) {
//                    $app['size'] = $this->subAppText($info);
//                }
//            }
            //下载地址
            $app['download_url'] = array_shift($appIcon->find('a'))->attr['href'];
        }

        $app["name"] = array_shift($d->find("h1 a"))->text();

        $types = $d->find('div.metaRight span.categoryicon a');
        $typesValue = array();

        $tags = '';
        foreach ($types as $type) {
            //数组 类别
            $typeText = $type->text();
            if (!empty($typeText)) {
                array_push($typesValue, $typeText);
            }

            $tags .= $typeText . ' ';
        }
        //标签
        $app['tag'] = $tags;

        $app['types'] = $typesValue;

        //配套图片
        $appImgs = $d->getElementById('iphone-screen-shots');
        if (!empty($appImgs)) {
            $images = $appImgs->find('img.image-screen-shots');

            $app['content_img'] = $this->getImgPath($images);
        } else {
            $images = $d->find('p img');
            $app['content_img'] = $this->getImgPath($images);
        }

        //content
        $contentText = $this->getContentText($d->find('p'));
//        dump($contentText);
//        return;
//        $app['content_text'] = str_replace('www.iappstoday.com', 'www.appbpp.com', str_replace('www.iapps.im', 'www.appbpp.com', $contentText['']));
        $app['content'] = $contentText['content'];
        $app['content_text'] = str_replace('iappstoday', 'appbpp', str_replace('iapps.im', 'appbpp.com', $contentText['content_text']));

        $comment = $html->find('#colLeft ul.commentlist');
        if (!empty($comment)) {
            $app['comment'] = array_shift($html->find('#colLeft ul.commentlist'))->outertext();
        }

        return $app;
    }

    private function getContentText($p) {
        $index = 0;

        $text = array();
        $contentText = '';
        foreach ($p as $val) {
            if (empty($val->children)) {
                $t = $val->text();
                if ($index == 0) {
                    $text['content'] = $t;
                }
                $contentText .= '<p>' . $t . '</p>';

                $index = 1;
            }
        }

        $text['content_text'] = $contentText;

        return $text;
//        $flag = 0;
//        $flagC = 0;
//        $content = array();
//        $text = '';
//        foreach ($child as $ch) {
//            if ($flag == 0 && 'h5' == $ch->tag) {
//                $flag = 1;
//            } elseif (($flag == 1 || $flag == 2) && 'p' == $ch->tag && empty($ch->children)) {
//                if ($flagC == 0) {
//                    $content['content'] = $ch->text();
//                }
//                $flagC = 1;
//                $text .= '<p>' . $ch->text() . '</p>';
//
//                $flag = 2;
//            } elseif ($flag == 2 && 'h5' == $ch->tag) {
//                $content['content_text'] = $text;
//
//                return $content;
//            }
//        }
//        return $content;
    }

    private function getImgPath($images) {
        $imagesPath = '';
        foreach ($images as $img) {
            $imagesPath .= $img->attr['src'] . ';';
        }

        return substr($imagesPath, 0, strlen($imagesPath));
    }

    /**
     * 再次免费
     * @return type 
     */
    function listFreeAgain() {
        $configService = new ConfigService();
        $freeAgainDate = $configService->getConfigValue('free_again_date');
        $freeAgain = $configService->getConfigValue('free_again');
        if (1 == $freeAgain && date('Y-m-d') == $freeAgainDate) {
            return false;
        }

        $html = file_get_html(ConstantUtil::$LOAD_APP_URL_HOT);
        if (!$html) {
            return;
        }

        $script = $html->find('script');
        $scriptText = (array_shift($script)->innertext());

        $script = split(',', $scriptText);

        $href = array();
        foreach ($script as $sc) {
            if (ereg('^href', $sc)) {
                $a = split(':', $sc);
                //if(ereg('^\"http:', $a[1])){
                array_push($href, trim(str_replace('"', '', $a[1] . ':' . $a[2])));
                //}
            }
        }


        //比对url表中数据
        //未添加进url表中数据集合
        $noneUrl = array();

        //未发布数据
        $noneApp = array();

        $urlsService = new UrlsService();
        //$appService = new AppService();

        foreach ($href as $value) {
            $url = $urlsService->findUrlsByUrl($value);

            if (is_null($url)) {
                array_push($noneUrl, array('url' => $value, 'type' => 'app', 'datetime' => date('Y-m-d H:m:s')));
            } else {
                //是否已经在App 中发布
                if (0 == $url['load_over']) {
                    array_push($noneApp, $url);
                } else {
                    $app = $this->findAppById($url['id']);

                    $app['fine'] = 1;
                    $app['date'] = date('Y-m-d');
                    $app['datetime'] = date('Y-m-d H:m:s');

                    $this->updateApp($app);
                }
            }
        }

        if (!empty($noneUrl)) {
            $urlsService->insertAll($noneUrl);
            foreach ($noneUrl as $url) {

                $this->insertReleaseApp($url, 1);

                sleep(10);
            }
        }

        //未发布App
        if (!empty($noneApp)) {
            foreach ($noneApp as $url) {

                $this->insertReleaseApp($url, 1);

                sleep(10);
            }
        }


        $configService->setConfigValue('free_again', 1);
        $configService->setConfigValue('free_again_date', date('Y-m-d'));

        return true;
    }

    /**
     * 获取App内容
     * @param type $rightDiv 
     */
    function getContent($url) {
        $app = array();
        $html = file_get_html($url);
        if (!$html) {
            return $html;
        }
        //获取时间
        $leftDiv = $html->find("#colLeft div.metaLeft");

        $app['datetime'] = date('Y-m-d H:m:s');

        //获取内容
        $rightDiv = $html->find("#colLeft div.postRight");

        $d = array_shift($rightDiv);

        $appIcon = $d->find('table.app-icon-line');
        if (!empty($appIcon)) {
            $appIcon = array_shift($appIcon);

            $app['app_icon'] = array_shift($appIcon->find('img'))->attr['src'];

            $appInfoText = $appIcon->text();
            $appInfoTextArray = split('  ', trim($appInfoText));
            foreach ($appInfoTextArray as $info) {
                if (ereg('价格', $info)) {
                    $app['price'] = $this->subAppText($info);
                } else if (ereg('系统', $info)) {
                    $app['version'] = $this->subAppText($info);
                } else if (ereg('大小', $info)) {
                    $app['size'] = $this->subAppText($info);
                }
            }

            //下载地址
            $app['download_url'] = array_shift($appIcon->find('a'))->attr['href'];
            //删除  精选限时免费应用......
            $appIcon->previousSibling(0)->clear();

            $appIcon->clear();
        }
        $app["name"] = array_shift($d->find("h1 a"))->text();

        $types = $d->find('div.metaRight span.categoryicon a');
        $typesValue = array();

        $tags = '';
        foreach ($types as $type) {
            //数组 类别
            $typeText = $type->text();
            array_push($typesValue, $typeText);

            $tags .= $typeText . ' ';
        }
        //标签
        $app['tag'] = $tags;

        $app['types'] = $typesValue;

        //删除一些内容
        $d->children(7)->clear();
        $d->children(3)->clear();
        $d->getElementById("ckepop")->clear();

        $wumiiDiv = $d->getElementById("wumiiLikeRecBtnDiv");
        //删除  每日优秀免费正版App推荐，尽在www.iappstoday.com

        $d->getElementById("wumiiLikeRecBtnDiv")->clear();
        $d->children(2)->clear();

        //删除  每天更新，这些应用再次免费啦..
        $iframe = $d->find('iframe');
        if (!empty($iframe)) {
            array_shift($iframe)->clear();
        }

        //配套图片
        $appImgs = $d->getElementById('iphone-screen-shots');
        if (!empty($appImgs)) {
            $images = $appImgs->find('img.image-screen-shots');

            $imagesPath = '';
            foreach ($images as $img) {
                $imagesPath .= $img->attr['src'] . ';';
            }

            $app['content_img'] = $imagesPath;
        }
        //
        //需要删除
        $logoText = 'iappstoday';

        $webText = 'www.iapps.im';
        $app["content"] = str_replace($webText, 'www.appbpp.com', str_replace($logoText, 'appbpp', $d->innertext()));
        $app["content_text"] = str_replace($webText, 'www.appbpp.com', str_replace($logoText, 'appbpp', trim($d->text())));
        $comment = $html->find('#colLeft ul.commentlist');
        if (!empty($comment)) {
            $app['comment'] = array_shift($html->find('#colLeft ul.commentlist'))->outertext();
        }

        return $app;
    }

    private function subAppText($text) {
        return trim(mb_substr(trim($text), 3, strlen(trim($text)), 'utf-8'));
    }

    function getAppTypeName($type) {
        if ('app' == $type || empty($type)) {
            return '应用';
        } else if ('game' == $type) {
            return '游戏';
        }

        return null;
    }

    function randApp($field = '*', $limit = 1) {
        $where['release'] = array('eq', 1);
        return D('app')->field($field)->where($where)->order('rand( )')->limit($limit)->select();
    }

}

?>
